package com.czwx.bee.business.manager.modular.sys.controller;


import com.czwx.bee.base.common.dto.ResponseDto;
import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.web.common.BaseController;
import com.czwx.bee.business.manager.config.security.JwtAuthenticationRequest;
import com.czwx.bee.business.manager.config.security.JwtTokenUtil;
import com.czwx.bee.business.manager.modular.borrow.dto.BorrowDto;
import com.czwx.bee.business.manager.modular.main.dto.LoginDto;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import com.czwx.bee.business.manager.modular.sys.service.UserService;
import com.czwx.bee.business.manager.utils.SecurityUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


@Api(value = "LoginController", tags = "登录相关")
@RestController
@Validated
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${jwt.refresh}")
    private Long refresh;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.header}")
    private String tokenHeader;

    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @ApiImplicitParam(name = "jwtAuthenticationRequest", value = "请输入用户名密码", required = true, dataType = "JwtAuthenticationRequest", paramType = "body")
    @PostMapping("/login")
    @ApiResponses(
            @ApiResponse(code = 200,message = "aaa",response=BorrowDto.class)
    )
    public ResponseDto createAuthenticationToken(@RequestBody @Validated JwtAuthenticationRequest jwtAuthenticationRequest, Device device) {
        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(jwtAuthenticationRequest.getUsername(), jwtAuthenticationRequest.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        final String token = jwtTokenUtil.generateToken(securityUser, device);

//        if (jwtAuthenticationRequest.getRememberMe()!=1) { // 记住我
            redisTemplate.opsForValue().set("token:"+token, securityUser, expiration, TimeUnit.SECONDS);
//        } else {
//            redisTemplate.opsForValue().set("token:"+token, securityUser, refresh, TimeUnit.SECONDS);
//        }
       LoginDto loginDto= new LoginDto();
        if(securityUser.getDrainageId()!=null){
            loginDto.setToken(token);
            loginDto.setCompanyName(securityUser.getCompanyName());
            loginDto.setName(securityUser.getRealName());
        }
        return new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION,loginDto);
    }

    @PostMapping("/token_logout")
    @ApiOperation(value = "注销用户", notes = "删除session及redis中Token", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "请输入凭证", required = true, dataType = "String", paramType = "header"),
    })
    public ResponseDto logout (HttpServletRequest request, HttpServletResponse response) {
        ResponseDto rs=new ResponseDto(BizExceptionEnum.SUCCESSFUL_OPERATION);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            new SecurityContextLogoutHandler().logout(request, response, auth);
        String token=request.getHeader(this.tokenHeader);
        redisTemplate.delete("token:"+token);
        return  rs;
    }




}
